# from django.shortcuts import render, HttpResponse

# Create your views here.
from django.conf import settings
from django.urls import path, re_path

from djmockserver.mock.match import mockitem_matcher
from djmockserver.mock.response import ResponseMaker
from djmockserver.mock.serializer import RequestSerializer
from djmockserver.mock.common import get_mock

import logging
# from functools import wraps
# import time
#
# def logtime(func):
#     count = 0
#     tcount = 0
#     @wraps(func)
#     def wrapper(*args, **kwargs):
#         t1 = time.time()
#         result = func(*args, **kwargs)
#         t2 = time.time()
#         td = t2 - t1
#         nonlocal count, tcount
#         count += 1
#         tcount += td
#         print('{} exec {} times in {} s'.format(func.__name__, count, tcount))
#         if count == 600:
#             count, tcount = 0, 0
#         return result
#     return wrapper
#
logger = logging.getLogger(__name__)
#
# @logtime
def mock(request):
    #####################
    # 1/ requestSerializer 反序列化请求
    req = RequestSerializer(request)
    logger.info('deserialize request : {}'.format(req.req))
    # 2/ mockItem mock数据, request/response/uri
    # 3/ mockLoader 加载数据 (返回{uri:[mockItem1, mockItem2, ...]})
    # 4/ matcher 应用jsoncompare对比requestSerializer.request 和 mockItem.request, 匹配返回mockItem
    matchitem = mockitem_matcher.match(req)
    logger.info('matched mock object : {}'.format(matchitem))
    # 5/ ResponseMaker 使用mockItem.response生成响应 , 可以设置为请求转发，如果匹配不到则转发到设置的目标地址
    resp = ResponseMaker(req, matchitem).response
    logger.info('return response object : {}'.format(resp))
    #####################
    return resp

def addMock():
    mock_urlpatterns = []
    content = get_mock(settings.MOCK_FILE_PATH)

    for mock_item in content:
        # 读取mockjson数据，动态添加mock uri，并映射到mock函数
        if mock_item.get('request').get('uri'):
            # django中匹配path是不需要左“/”的
            uri = mock_item.get('request').get('uri').lstrip('/')
            mock_urlpatterns.append(path(uri, mock))
        else:
            # 正则匹配路由
            re_uri = mock_item.get('request').get('re_uri')
            mock_urlpatterns.append(re_path(re_uri, mock))

    logger.info('mock.json append uri : {}'.format(mock_urlpatterns))
    return mock_urlpatterns